import React, { useState } from 'react';
import { Button, Col, Form, Input, Row, Card, message } from 'antd';
import { useNavigate } from 'react-router-dom';

import { sendCaptcha, forgetPassword } from '@/api/auth';
import { COLOR_THEME } from '@/config/theme';
import './index.scss';

const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 8,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};
function ForgetPassword() {
    const [form] = Form.useForm();
    const navigator = useNavigate();
    // 倒计时剩余时间
    const [captchaCooldown, setCaptchaCooldown] = useState(0);
    // 发送状态
    const [isSendingCaptcha, setIsSendingCaptcha] = useState(false);
    const onFinish = (values) => {
        const reqParams = {
            email: values?.email,
            password: values?.password,
            code: values?.captcha,
        };
        try {
            forgetPassword(reqParams).then((res) => {
                if (res.code === 200) {
                    message.success('密码修改成功');
                    navigator('/auth/login');
                }
            });
        } catch (error) {
            console.error('修改密码失败:', error);
        }
    };
    // 发送验证码处理函数
    const handleSendCaptcha = async () => {
        try {
            // 验证邮箱字段
            const email = form.getFieldValue('email');
            if (!email || !/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email)) {
                form.setFields([
                    {
                        name: 'email',
                        errors: ['请输入有效的邮箱地址'],
                    },
                ]);
                return;
            }

            setIsSendingCaptcha(true);
            // 调用发送验证码接口
            await sendCaptcha({ email: email });
            message.success('验证码已发送至您的邮箱');

            // 开始倒计时
            let countdown = 60;
            setCaptchaCooldown(countdown);
            const timer = setInterval(() => {
                countdown -= 1;
                setCaptchaCooldown(countdown);
                if (countdown <= 0) {
                    clearInterval(timer);
                }
            }, 1000);
        } catch (error) {
            console.error('发送验证码失败:', error);
        } finally {
            setIsSendingCaptcha(false);
        }
    };
    return (
        <div className="forgetPassword">
            <Card
                className="forgetPassword-card"
                style={{
                    backgroundColor: `${COLOR_THEME.QUATERNARY}50`,
                }}
            >
                <Form
                    {...formItemLayout}
                    form={form}
                    name="forgetPassword"
                    onFinish={onFinish}
                    initialValues={{
                        residence: ['zhejiang', 'hangzhou', 'xihu'],
                        prefix: '86',
                    }}
                    style={{
                        maxWidth: 600,
                    }}
                    scrollToFirstError
                >
                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            {
                                type: 'email',
                                message: '邮箱输入格式有误!',
                            },
                            {
                                required: true,
                                message: '请输入您的邮箱!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="新密码"
                        rules={[
                            {
                                required: true,
                                message: '请输入您的密码!',
                            },
                        ]}
                        hasFeedback
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        name="confirm"
                        label="确认新密码"
                        dependencies={['password']}
                        hasFeedback
                        rules={[
                            {
                                required: true,
                                message: '请再次输入您的密码!',
                            },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两个密码不一致!'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item label="验证码">
                        <Row gutter={8}>
                            <Col span={12}>
                                <Form.Item
                                    name="captcha"
                                    noStyle
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入验证码!',
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Button onClick={handleSendCaptcha} disabled={captchaCooldown > 0 || isSendingCaptcha}>
                                    {isSendingCaptcha
                                        ? '发送中...'
                                        : captchaCooldown > 0
                                          ? `${captchaCooldown}秒后重试`
                                          : '发送验证码'}
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    {/* <Form.Item
            name="agreement"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
              },
            ]}
            {...tailFormItemLayout}
          >
            <Checkbox>
              I have read the <a href="">agreement</a>
            </Checkbox>
          </Form.Item> */}
                    <Form.Item {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit">
                            提 交
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
}
export default ForgetPassword;
